package top.maochang.hou.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "FilterRequest",urlPatterns = "/*")
@Slf4j
public class FilterRequest implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器初始化");
    }

    public void destroy() {
        System.out.println("过滤器销毁");
    }

    @Override

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        //0.请求转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1、获取本次请求的URI
        String requestURI = req.getRequestURI();
        //3.定义不需要处理的请求路径
        String[] urls = new String[]{
                "/assets",
                "/page",
                "index.jsp"
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);

        //3、如果不需要处理，则直接放行
        if(check){
        //log.info("本次请求{}不需要处理过滤处理--css+html请求",requestURI);
        }else {
           // log.info("本次请求{}需要处理过滤处理",requestURI);
            request.getRequestDispatcher("utf-8");
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/html;charset=utf-8");
        }
        //4、放行
        chain.doFilter(request,response);
        return;
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            //System.out.println(url.contains(requestURI));
            if(requestURI.contains(url)){
                return true;
            }
        }
        return false;
    }
}
